<template>
  <div>
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/admin/questionBankManage' }">题库</el-breadcrumb-item>
      <el-breadcrumb-item>{{bankName}}</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="subjectTitle">
      <el-collapse style="margin-left: 5%;" v-model="activeNames" @change="handleChange">
        <el-collapse-item title="筛选题目" name="1">
          <div class="check-box">知识点：
            <el-radio-group v-model="searchForm.knowledgePointId">
              <el-radio v-for="item in knowledgePoints"
                        :key="item.id"
                        :label="item.id">{{item.name}}</el-radio>
            </el-radio-group>
          </div>
          <div class="check-box">题型：
            <el-radio-group v-model="searchForm.questionType">
              <el-radio v-for="item in types"
                        :key="item.value"
                        :label="item.value">{{item.name}}</el-radio>
            </el-radio-group>
          </div>
          <el-link type="info" @click="clearSearch">清空</el-link>
        </el-collapse-item>
      </el-collapse>
      <el-button type="primary" style="margin-left:5%; height: 50px;" @click="search">搜索题目</el-button>
      <el-button type="primary" v-if="bankStatus === '1'" @click="confirmDialogVisible = true" style="margin-left: 5%; margin-right: 5%; height: 50px">审核</el-button>
      <el-button type="danger" v-if="bankStatus === '2'" @click="cancelDialogVisible = true" style="margin-left: 5%; margin-right: 5%; height: 50px">撤销审核</el-button>
    </div>
    <div style="width: 90%; margin-left: 5%; margin-top: 10px;">
      <el-table
        :data="questionList"
        style="width: 100%">
        <el-table-column prop="stemShow" label="题目"></el-table-column>
        <el-table-column prop="subject" label="科目" width="130"></el-table-column>
        <el-table-column prop="knowledgePoint" label="知识点" width="130"></el-table-column>
        <el-table-column prop="teacherNumber" label="老师" width="130"></el-table-column>
        <el-table-column label="题型" width="130">
          <template slot-scope="scope">
            <span>{{transferType(scope.row.questionType)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" prop="updateTimeShow" width="140">
        </el-table-column>
        <el-table-column label="操作" width="140">
          <template slot-scope="scope" style="display: grid; grid-template-columns: 50% 50%">
            <el-link type="info" @click="detailQuestion(scope.row)">查看</el-link>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          layout="total, prev, pager, next"
          :page-size="pagination.page_size"
          :current-page="pagination.index"
          :total="pagination.total"
          @current-change="changePage">
        </el-pagination>
      </div>
    </div>

    <!--  预览题目  -->
    <el-dialog
      title="查看题目"
      :visible.sync="detailDialogVisible"
      width="50%"
      center>
      <div class="detail">
        <div class="title"><i class="el-icon-s-order"></i>科目</div>
        <span class="text">{{questionDetail.subject}}</span>
        <div class="title"><i class="el-icon-s-order"></i>知识点</div>
        <span class="text">{{questionDetail.knowledgePoint}}</span>
        <div class="title"><i class="el-icon-s-order"></i>题目</div>
        <span class="text">{{questionDetail.stem}}</span>
        <!--   单选选项   -->
        <div class="text" v-if="questionDetail.questionType === 'radio' || questionDetail.questionType === 'multiple'">A.{{questionDetail.options.A}}</div>
        <div class="text" v-if="questionDetail.questionType === 'radio' || questionDetail.questionType === 'multiple'">B.{{questionDetail.options.B}}</div>
        <div class="text" v-if="questionDetail.questionType === 'radio' || questionDetail.questionType === 'multiple'">C.{{questionDetail.options.C}}</div>
        <div class="text" v-if="questionDetail.questionType === 'radio' || questionDetail.questionType === 'multiple'">D.{{questionDetail.options.D}}</div>
        <div class="title"><i class="el-icon-s-order"></i>答案</div>
        <div class="text">{{questionDetail.answer}}</div>
      </div>
    </el-dialog>

    <!--  审核确认  -->
    <el-dialog
      title="提示"
      :visible.sync="confirmDialogVisible"
      width="30%"
      :before-close="handleDialogClose">
      <span>是否通过本题库审核？</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="verifyConfirm()">同 意</el-button>
      </span>
    </el-dialog>

    <!--  撤销确认  -->
    <el-dialog
      title="提示"
      :visible.sync="cancelDialogVisible"
      width="30%"
      :before-close="handleDialogClose">
      <span>是否撤销本题库？</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="danger" @click="cancelConfirm()">撤 销</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getKnowledgePoints,
  questionsSearchByBank,
  findSubjectByName
} from '../../../api/questions'
import {verify, cancel} from '../../../api/adminManage'

export default {
  name: 'QuestionManage',
  data () {
    return {
      confirmDialogVisible: false,
      cancelDialogVisible: false,
      // 科目
      subject: '',
      subjectId: 0,
      // 预览题目
      detailDialogVisible: false,
      questionDetail: {},
      // 分页信息
      pagination: {
        page_size: 5,
        index: 1,
        total: 100
      },
      paginationAdd: {
        page_size: 5,
        index: 1,
        total: 100
      },
      // 筛选条件
      activeNames: [],
      searchForm: {
        subjectId: null,
        knowledgePointId: null,
        teacherId: null,
        questionType: null,
        examQuestion: null,
        updateTime: null
      },
      // 其他条件
      types: [
        {
          name: '单选',
          value: 'radio'
        },
        {
          name: '多选',
          value: 'multiple'
        },
        {
          name: '填空',
          value: 'filling'
        },
        {
          name: '简答',
          value: 'shortAnswer'
        }
      ],
      subjects: [],
      knowledgePoints: [],
      // 表格显示
      bankId: 0,
      bankName: '',
      bankStatus: '',
      questionList: [
        {
          answer: 'A',
          createTime: '2022-03-24 14:18:34',
          id: 1,
          knowledgePointId: 2,
          questionStem: '{"stem":"192.168.1.0/24 使用掩码255.255.255.240 划分子网，其可用子网数为（ ），每个子网内可用主机地址数为（ ）。","options":{"A":"14 14","B":"16 14","C":"254 6","D":"14 62"}}',
          questionType: 'radio',
          subjectId: 1,
          teacherId: 1,
          updateTime: '2022-03-24 14:18:34',
          examQuestion: false,
          stem: '92.168.1.0/24 使用掩码255.255.255.240 划分子网，其可用子网数为（ ），每个子网内可用主机地址数为（ ）。',
          options: {
            A: '',
            B: '',
            C: '',
            D: ''
          }
        }
      ]
    }
  },
  mounted () {
    this.bankId = this.$route.query.id
    this.bankName = this.$route.query.name
    this.subject = this.$route.query.subject
    this.bankStatus = this.$route.query.status
    this.getQuestionsByBank()
    this.getUsefulInfo()
  },
  methods: {
    // 获取所有题目
    getQuestionsByBank () {
      let parameter = {
        page_size: this.pagination.page_size,
        index: this.pagination.index - 1,
        questionBankId: this.bankId
      }
      questionsSearchByBank(parameter).then(res => {
        if (res.data.errorCode === 0) {
          console.log(res.data)
          this.questionList = res.data.data.list
          this.pagination.total = res.data.data.total
          // 转化格式
          for (let i = 0; i < this.questionList.length; i++) {
            this.questionList[i].stemShow = this.transferForm(this.questionList[i])
            this.questionList[i].stem = JSON.parse(this.questionList[i].questionStem).stem
            this.questionList[i].options = JSON.parse(this.questionList[i].questionStem).options
            this.questionList[i].updateTimeShow = this.transferTime(this.questionList[i])
          }
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 翻页
    changePage (val) {
      this.pagination.index = val
      this.getQuestionsByBank()
    },
    // 预览题目
    detailQuestion (questionDetail) {
      this.questionDetail = questionDetail
      this.detailDialogVisible = true
    },
    // 通过科目获取知识点
    getKnowledgePointBySubject (subjectId) {
      getKnowledgePoints(subjectId).then(res => {
        console.log(res.data)
        if (res.data.errorCode === 0) {
          this.knowledgePoints = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    getUsefulInfo () {
      findSubjectByName(this.subject).then(res => {
        console.log(res.data)
        if (res.data.errorCode === 0) {
          this.subjectId = res.data.data.id
          this.getKnowledgePointBySubject(res.data.data.id)
          this.getAllQuestionAdd(res.data.data.id)
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 搜索
    handleChange (val) {
      console.log(val)
    },
    // 搜索
    clearSearch () {
      this.searchForm = {
        knowledgePointId: null,
        teacherId: null,
        questionType: null,
        updateTime: null
      }
      this.getQuestionsByBank()
    },
    search () {
      this.pagination = {
        page_size: 5,
        index: 1,
        total: 100
      }
      let parameter = {
        page_size: this.pagination.page_size,
        index: this.pagination.index - 1,
        questionBankId: this.bankId,
        knowledgePointId: this.searchForm.knowledgePointId,
        questionType: this.searchForm.questionType
      }
      questionsSearchByBank(parameter).then(res => {
        if (res.data.errorCode === 0) {
          console.log(res.data)
          this.questionList = res.data.data.list
          this.pagination.total = res.data.data.total
          // 转化格式
          for (let i = 0; i < this.questionList.length; i++) {
            this.questionList[i].stemShow = this.transferForm(this.questionList[i])
            this.questionList[i].stem = JSON.parse(this.questionList[i].questionStem).stem
            this.questionList[i].options = JSON.parse(this.questionList[i].questionStem).options
            this.questionList[i].updateTimeShow = this.transferTime(this.questionList[i])
          }
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 转化格式
    transferForm (questionDetail) {
      let stem = JSON.parse(questionDetail.questionStem)
      let temp = stem.stem
      var count = 0
      for (var i = 0; i < temp.length; i++) {
        // eslint-disable-next-line no-control-regex
        if (temp.charAt(i).replace(/[^\x00-\xff]/g, 'rr').length > 1) {
          count += 2
        } else {
          count += 1
        }
        if (count >= 50) {
          return temp.slice(0, i) + '...'
        }
      }
      return temp
    },
    transferTime (questionDetail) {
      return questionDetail.updateTime.slice(0, 10)
    },
    transferType (type) {
      switch (type) {
        case 'radio': return '单选'
        case 'multiple': return '多选'
        case 'filling': return '填空'
        case 'shortAnswer': return '简答'
        default: return 'error'
      }
    },
    handleDialogClose () {
      this.confirmDialogVisible = false
      this.cancelDialogVisible = false
    },
    verifyConfirm () {
      let that = this
      verify(this.bankId)
        .then(res => {
          console.log(res)
          if (res.data.errorCode === 0) {
            that.$message({
              message: '审核成功！',
              type: 'success'
            })
            that.confirmDialogVisible = false
          } else {
            that.$message.error(res.data.message)
          }
        })
    },
    cancelConfirm () {
      let that = this
      cancel(this.bankId)
        .then(res => {
          console.log(res)
          if (res.data.errorCode === 0) {
            that.$message({
              message: '撤销审核成功！',
              type: 'success'
            })
            that.cancelDialogVisible = false
          } else {
            that.$message.error(res.data.message)
          }
        })
    }
  }
}
</script>

<style scoped>
  .breadcrumb {
    padding: 20px;
  }

  .subjectTitle {
    font-size: 16px;
    font-weight: bold;
    margin: 0 20px;
    display: grid;
    grid-template-columns: 80% 10% 10%;
  }

  .title {
    margin-top: 10px;
    margin-left: 10px;
    font-size: 15px;
    font-weight: bolder;
  }

  .text {
    margin-top: 10px;
    margin-bottom: 10px;
    margin-left: 20px;
    font-size: 15px;
  }

  .check-box {
    margin-bottom: 5px;
    text-align: left;
  }
</style>
